package com.starsea.book.ui.newpage

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.lxj.xpopup.XPopup
import com.starsea.book.R
import com.starsea.book.base.VMBaseFragment
import com.starsea.book.databinding.FragmentWelfareBinding
import com.starsea.book.databinding.LayoutWelfareFooterBinding
import com.starsea.book.databinding.LayoutWelfareHeaderBinding
import com.starsea.book.ui.browser.WebViewActivity
import com.starsea.book.ui.main.MainActivity
import com.starsea.book.ui.main.MainFragmentInterface
import com.starsea.book.ui.newpage.activity.LotteryTiggerActivity
import com.starsea.book.ui.newpage.activity.SignDetailsActivity
import com.starsea.book.ui.newpage.adapter.HomeWelfareAdapter
import com.starsea.book.ui.newpage.entity.SignBaseInfoEntity
import com.starsea.book.ui.newpage.pop.ActivityPop
import com.starsea.book.ui.newpage.pop.NewUserPop
import com.starsea.book.ui.newpage.pop.NewVersionPop
import com.starsea.book.ui.newpage.pop.WelfareGetCoinPop
import com.starsea.book.ui.newpage.pop.WelfareSignPop
import com.starsea.book.ui.newpage.utils.Singleton
import com.starsea.book.ui.newpage.utils.finialDouble
import com.starsea.book.ui.newpage.viewmodel.WelfareViewModel
import com.starsea.book.ui.newpage.weidget.countdownview.CountdownView
import com.starsea.book.ui.newpage.weidget.countdownview.DynamicConfig
import com.starsea.book.utils.openUrl
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import com.starsea.book.utils.visible


/**
 * @author Lee
 * @createTime 2023-12-26 09 GMT+8
 * @desc :
 */
class WelfareFragment() : VMBaseFragment<WelfareViewModel>(R.layout.fragment_welfare),
    MainFragmentInterface {

    lateinit var mAdapter: HomeWelfareAdapter
    private val binding by viewBinding(FragmentWelfareBinding::bind)
    override val viewModel by activityViewModels<WelfareViewModel>()

    var page = 1

    var boxInfo: SignBaseInfoEntity? = null

    var signRecordId = ""

    constructor(position: Int) : this() {
        val bundle = Bundle()
        bundle.putInt("position", position)
        arguments = bundle
    }

    var headerBinding: LayoutWelfareHeaderBinding? = null
    var footerBinding: LayoutWelfareFooterBinding? = null

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        mAdapter = HomeWelfareAdapter(requireContext()) {
            when (it.ruleType) {
                2 -> {
                    viewModel.getNewUser()
                }

                4 -> {
//                    viewModel.getNewUser()
                }

                12, 13 -> {

//                    Download.start(requireContext(), url, name)
//                    postEvent(EventBus.NOTIFY_MAIN_CHANGE_INDEX, 4)

                    startActivity<MainActivity> {
                        putExtra("index", 3)
                    }

                }

                16 -> {
                    startActivity<LotteryPanActivity> {

                    }
                }

                17 -> {
                    startActivity<LotteryTiggerActivity> {

                    }
                }
            }
        }

        binding.rvContent.layoutManager = LinearLayoutManager(requireContext())

        binding.rvContent.adapter = mAdapter

        headerBinding =
            LayoutWelfareHeaderBinding.inflate(layoutInflater, binding.rvContent, false)

        footerBinding =
            LayoutWelfareFooterBinding.inflate(layoutInflater, binding.rvContent, false)

        mAdapter.addHeaderView {
            headerBinding!!
        }

        mAdapter.addFooterView {
            footerBinding!!
        }

        headerBinding!!.tvCheckDetails.setOnClickListener { startActivity<SignDetailsActivity> { } }


//        viewModel.getNewUser()

//
//        viewModel.checkUpdate()

        viewModel.checkActivity("1")

        binding.atOpenBx.setOnClickListener {
            if (boxInfo == null) {
                return@setOnClickListener
            }

            val time = Singleton.getTimeMins(boxInfo!!.openTime ?: "0")

            if ((time - System.currentTimeMillis()) > 0) {
                XPopup.Builder(requireContext())
                    .asCustom(
                        WelfareGetCoinPop(
                            requireContext(),
                            boxInfo!!.adver ?: 2,
                            true,
                            (boxInfo!!.amount ?: "0").toDouble().finialDouble(),
                            (boxInfo!!.adverInfo!!.amount ?: "0").toDouble().finialDouble(),
                            boxInfo!!.recordId!!
                        ) {

                            showAdaVideo(boxInfo!!.recordId!!, 2)

                        }
                    ).show()
            } else {
                viewModel.openBox()
            }


        }


        binding.swRefresh.setOnRefreshListener {
            page = 1

        }

        binding.swRefresh.setOnLoadMoreListener {
            page++

        }

        headerBinding!!.tvCheck.setOnClickListener {
            startActivity<MyWalletActivity> { }
        }

        viewModel.checkUpdateResult.observe(this) { data ->
            if (data.status == 200) {
                if (data.data == null) {

                } else {
                    XPopup.Builder(requireActivity())
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            NewVersionPop(
                                requireContext(),
                                data.data!!.eventContent ?: "",
                                data.data!!.eventUrl ?: ""
                            ) { type, url ->
                                if (type == 0) {

                                } else {
                                    requireActivity().openUrl(url)
                                }
                            }
                        )
                        .show()
                }
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }
        viewModel.advertResult.observe(this) {
            if (it.status == 200) {
                viewModel.getBoxDetails()
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(it.msg)
            }
        }
        viewModel.dataListResult.observe(this) {
            if (it.status == 200) {
                if (page == 1) {
                    mAdapter.setItems(it.data)
                    binding.swRefresh.finishRefresh()
                } else {
                    mAdapter.addItems(it.data!!)
                }

                binding.swRefresh.finishLoadMore()
//                if ((it.data?.size ?: 0) < 10) {
                binding.swRefresh.finishLoadMoreWithNoMoreData()
//                }

            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(it.msg)
            }
        }
        viewModel.signInfoResult.observe(this) { data ->
            if (data.status == 200) {

                headerBinding!!.tvSignTitle.text =
                    "立即签到+${(data.data!!.today!!.amount ?: "0").toDouble().finialDouble()}金币"

                headerBinding!!.tvSignTitle.text =
                    "继续签到最高可得${
                        (data.data!!.maxAmount ?: "0").toDouble().finialDouble()
                    }金币"

                headerBinding!!.tvSign.setOnClickListener {
                    if (data.data!!.sign!!) {
                        viewModel.signList()
                    } else {
                        data.data!!.sign = true
                        viewModel.sign()
                    }
                }
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.checkActivityResult.observe(this) { data ->
            if (data.status == 200) {
                if (!data.data!!) {
                    viewModel.getActivity()
                } else {
                    viewModel.checkUpdate()
                }
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }
        viewModel.getActivityResult.observe(this) { data ->
            if (data.status == 200) {

                if (data.data != null) {
                    XPopup.Builder(requireActivity())
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            ActivityPop(
                                requireContext(),
                                data.data!!.eventContent ?: "",
                                data.data!!.eventImg ?: "",
                                data.data!!.eventName ?: "",
                                data.data!!.eventUrl ?: ""
                            ) { type, url ->
                                if (type == 0) {
                                    viewModel.checkActivity("0")
                                } else {
                                    viewModel.checkActivity("0")
                                    startActivity<WebViewActivity> {
                                        putExtra("title", data.data!!.eventName)
                                        putExtra("url", url)
//                                        IntentData.put(it, ReadBook.bookSource?.getHeaderMap(true))
                                    }
                                }
                            }
                        )
                        .show()
                } else {
                    viewModel.checkUpdate()
                }

            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.signResult.observe(this) { data ->
            if (data.status == 200) {
                viewModel.signList()
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.signListResult.observe(this) { data ->
            if (data.status == 200) {

                XPopup.Builder(requireContext())
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        WelfareSignPop(
                            requireContext(),
                            data.data!!.today!!,
                            data.data!!.welfareData!!
                        ) {
                            showAdaVideo(data.data!!.today!!.recordId ?: "", 1)
                        })
                    .show()


            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }
        viewModel.newUserListResult.observe(this) { data ->
            if (data.status == 200) {

//                if (!data.data!!.sign!!)
                XPopup.Builder(requireContext())
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        NewUserPop(
                            requireContext(),
                            data.data!!.startDate ?: "",
                            data.data!!.endDate ?: "",
                            data.data!!.sign!!,
                            data.data!!.welfareData!!
                        ) {
                            if (it == 1) {
                                viewModel.newUserSign()
                            }
                        })
                    .show()


            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }
        viewModel.newUserSignResult.observe(this) { data ->
            if (data.status == 200) {
                toastOnUi("领取成功")
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.boxDetailsResult.observe(this) { data ->
            if (data.status == 200) {
                com.blankj.utilcode.util.LogUtils.e(">>>> ", data.data!!.toString())

                val time = Singleton.getTimeMins(data.data!!.openTime ?: "0")

                boxInfo = data.data

                refreshTime(time - System.currentTimeMillis())

                com.blankj.utilcode.util.LogUtils.e(">>>> ", data.data!!.openTime)

            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.openBoxResult.observe(this) { data ->
            if (data.status == 200) {

                boxInfo = data.data

                XPopup.Builder(requireContext())
                    .asCustom(
                        WelfareGetCoinPop(
                            requireContext(),
                            data.data!!.adver ?: 2,
                            false,
                            (data.data!!.amount ?: "0").toDouble().finialDouble(),
                            (data.data!!.adverInfo!!.amount ?: "0").toDouble().finialDouble(),
                            data.data!!.recordId ?: ""
                        ) {
                            showAdaVideo(data.data!!.recordId ?: "", 2)
                        }
                    ).show()


                com.blankj.utilcode.util.LogUtils.e(">>>> ", data.data!!.toString())

                val time = Singleton.getTimeMins(data.data!!.openTime ?: "0")

                refreshTime(time - System.currentTimeMillis())

                com.blankj.utilcode.util.LogUtils.e(">>>> ", data.data!!.openTime)

            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(data.msg)
            }
        }
    }

    private fun showAdaVideo(data: String, type: Int) {
        showLoading("广告加载中...")
        //创建TTAdNative对象，createAdNative(Context context) context需要传入Activity对象
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(requireActivity())

        val adSlot = AdSlot.Builder()
            .setCodeId("956204408")
            .setOrientation(TTAdConstant.VERTICAL)
            .setAdLoadType(TTAdLoadType.LOAD)
            .build()


        mTTAdNative.loadRewardVideoAd(adSlot,
            object : TTAdNative.RewardVideoAdListener {
                override fun onError(p0: Int, p1: String?) {
                    LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1}")
                }

                override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                }

                override fun onRewardVideoCached() {
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?) {
                    dismissLoading()
                    ttRewardVideoAd!!.showRewardVideoAd(requireActivity())

                    ttRewardVideoAd.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            LogUtils.e(">>>> 广告展示")
                            // 广告展示
                        }

                        override fun onAdVideoBarClick() {
                            // 广告点击
                            LogUtils.e(">>>> 广告点击")
                        }

                        override fun onAdClose() {
                            // 广告关闭
                            LogUtils.e(">>>> 广告关闭")
                        }

                        override fun onVideoComplete() {
                            LogUtils.e(">>>> 广告素材播放完成，例如视频未跳过，完整的播放了")
                        }

                        override fun onVideoError() {
                            LogUtils.e(">>>> 广告展示时出错")
                        }

                        override fun onRewardVerify(
                            p0: Boolean,
                            p1: Int,
                            p2: String?,
                            p3: Int,
                            p4: String?
                        ) {
                        }

                        // 奖励发放
                        override fun onRewardArrived(
                            p0: Boolean,
                            p1: Int,
                            p2: Bundle?
                        ) {
                            toastOnUi("奖励已发放")

                            LogUtils.e(">>>> data = $data")
                            viewModel.adverReward(data, type)

                            LogUtils.e(">>>> 奖励发放")
                            LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1} \n ")
                        }

                        // // 用户在观看时点击了跳过
                        override fun onSkippedVideo() {
                            LogUtils.e(">>>> 用户在观看时点击了跳过")
                        }

                    })
                }
            })

        //                                .setAdLoadType(TTAdConstant.PRELOAD)
        //                            AdSlot adSlot = new AdSlot.Builder()
        //                                .setCodeId(codeId)
        //                            //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
        //                            且仅是模板渲染的代码位ID使用，非模板渲染代码位切勿使用
        //                            .setExpressViewAcceptedSize(500,500)
        //                            .setSupportDeepLink(true)
        //                            .setOrientation(orientation)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
        //                            .setAdLoadType(PRELOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
        //                            .build();
    }


    override fun onResume() {
        super.onResume()
        viewModel.getTaskList()
        viewModel.getSignBaseInfo()
        viewModel.getBoxDetails()

    }

    override val position: Int? get() = arguments?.getInt("position")


    fun refreshTime(leftTime: Long) {

        val dynamicConfigBuilder: DynamicConfig.Builder = DynamicConfig.Builder()
        var isShowDay = false
        isShowDay = leftTime > 24 * 60 * 60 * 1000
        dynamicConfigBuilder
            .setShowDay(isShowDay)
            .setShowHour(false)
        binding.cvCount.visible(true)
        binding.cvCount.dynamicShow(dynamicConfigBuilder.build())
        if (leftTime > 0) {
            binding.cvCount.start(leftTime)
            binding.cvCount.restart()
        } else {
            binding.cvCount.visible(false)
            binding.cvCount.stop()
            binding.cvCount.allShowZero()
        }

        binding.cvCount.setOnCountdownEndListener(object : CountdownView.OnCountdownEndListener {
            override fun onEnd(cv: CountdownView?) {

                binding.cvCount.visible(false)
            }
        })

    }

}